#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define N 128
int prase_string (char *ptr, char *delim, char *arr[], int n);

int main (void)
{
	char *lineptr = NULL;
	size_t n;
	ssize_t ret = 0;
	char *arr[N] = {0};
	pid_t pid;
	while (1) {
		printf ("[%s@%s]$ ",getenv("PWD"), getenv("LOGNAME"));
		//读命令
		ret = getline (&lineptr, &n, stdin);
		if (-1 == ret) {
			perror ("getline()");
			break;
		}
		if (!strcmp ("exit\n", lineptr)) {
			break;
		}
		//解析命令
		prase_string (lineptr, " \t\n", arr, N);

		pid = fork ();
		if (-1 == pid) {
			perror ("fork()");
			return -1;
		}
		if (0 == pid) {
			//进程映像替换
			execvp (arr[0], arr);
			perror ("execvp()");
			exit(1);
		}
		wait (NULL);
	}
	
	free (lineptr);
	lineptr = NULL;
	return 0;
}

//将ptr字符串进行分割, 按照delim进行分割, 切割完的子串保存到arr中, 数组容纳n个元素
int prase_string (char *ptr, char *delim, char *arr[], int n)
{
	int i = 0;
	memset (arr, 0, n * sizeof (char *));
	while (i <= n - 1) {
		arr[i] = strtok (ptr, delim);
		if (NULL == arr[i]) {
			break;
		}
		if (arr[i] == "") {
			continue;
		}
		i++;
		ptr = NULL;
	}
	return 0;
}












